import { useEffect, useState, useCallback } from 'react';
import { useDispatch } from 'umi';

function updateTreeData(list, key, children) {
  return list.map((node) => {
    if (node.value === key) {
      return { ...node, children };
    }
    if (node.children) {
      return { ...node, children: updateTreeData(node.children, key, children) };
    }
    return node;
  });
}

const useOrgTreeSelect = () => {
  const [treeData, setTreeData] = useState([]);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({
      type: 'common/getOrgRootTree',
    }).then((data) => {
      setTreeData(data);
    });
  }, [dispatch]);

  const onLoadData = useCallback((data) => {
    const { key, children } = data;
    return new Promise((resolve) => {
      if (children) {
        resolve();
        return;
      }
      dispatch({
        type: 'common/getChildOrgListByParentId',
        payload: {
          parentId: key,
        },
      }).then((childData) => {
        if (childData && childData.length > 0) {
          const newList = updateTreeData(treeData, key, childData);
          setTreeData(newList);
          resolve();
        }
      });
    });
  }, [dispatch, treeData]);

  return [treeData, onLoadData];
};

export default useOrgTreeSelect;
